#include "ccirc.h"

ccirc::ccirc(unsigned int size)
{
	isEmpty = true;
	data = new unsigned char[size];
    this->size = size;
    ptr_first = data;
	ptr_end = data;
	read_index = data;
    last_read_index = 0;
}

ccirc::~ccirc(void)
{
}

void ccirc::addToBuffer(char inData)
{
   if (this->isEmpty)
   {
      this->isEmpty = false;
   }
   else
   {
      this->ptr_end = this->data +
            (((this->ptr_end - this->data) + 1) % this->size);
	  this->read_index = this->ptr_first;
   }

   *(this->ptr_end) = inData;

}

int ccirc::readNext(unsigned char * outData)
{
   if (this->isEmpty || this->read_index == 0)
   {
      return -1;
   }


   *outData = *(this->read_index);

   if (this->read_index == this->ptr_end)
   {
       if(this->ptr_end >= this->data + this->size)
       {
           this->ptr_first = this->data;
       }
       else
       {
           this->ptr_first = this->ptr_end +1;
       }
      this->read_index = 0;
   }
   else
   {
      if (this->read_index - (this->size + this->data-1) == 0)
      {
		  this->read_index = this->data;
      }

      else
      {
         this->read_index = this->read_index + 1;
      }
	  this->ptr_first = this->read_index;
   }

   

   return 0;
}
